package com.lw.easyexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.lw.easyexcel.mapper.UserMapper;
import com.lw.easyexcel.pojo.User;
import com.lw.easyexcel.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description:
 * @ClassName: UserController
 * @Author: lanwei
 * @Date: 2022/12/28 15:07
 */
@RestController
@RequestMapping("/user")
public class UserController {

    public static final int pageSize = 50000;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;


    @RequestMapping("/export")
    public void excelOutPu3(HttpServletResponse response) throws UnsupportedEncodingException {
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码
        String fileName = URLEncoder.encode("测试导出", "UTF-8");
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        //获取数据总条数
        int totalCount = userMapper.selectCount(new User());

        ExcelWriter excelWriter = null;
        try {
            //这里EasyExcel.write()方法第一个参数是输出流
            excelWriter = EasyExcel.write(response.getOutputStream(), User.class).build();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //需要的sheet页个数
        int sheetNum = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1 ;

        final long start = System.currentTimeMillis();
        for (int i = 1; i < sheetNum +1 ; i++) {
            List<User> userByPage = userService.getUserByPage(i);
            //sheet
            WriteSheet sheet = EasyExcel.writerSheet(i, "详细数据【"+(i)+"】").build();
            excelWriter.write(userByPage,sheet);
        }

        excelWriter.finish();
        System.out.println("导出成功");
        System.out.println("导出"+ totalCount +"条数据到excel,总花费" + (System.currentTimeMillis() - start) + "ms");
    }
}
